#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Software: PyCharm
# @Version : Python-
# @Author  : Shengji He
# @Email   : hsjbit@163.com
# @File    : BinaryTreeLevelOrderTraversal2.py
# @Time    : 2020/9/6 10:59
# @Description:
from typing import List
from collections import defaultdict, deque


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
        """
        Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right,
        level by level from leaf to root).

        For example:
            Given binary tree [3,9,20,null,null,15,7],
                3
               / \
              9  20
                /  \
               15   7
            return its bottom-up level order traversal as:
            [
              [15,7],
              [9,20],
              [3]
            ]

        :param root:
        :return:
        """
        # ans = defaultdict(list)
        # def helper(root: TreeNode, level):
        #     if not root:
        #         return
        #     ans[level].append(root.val)
        #     if root.left or root.right:
        #         helper(root.left, level + 1)
        #         helper(root.right, level + 1)
        #
        # helper(root, 0)
        # ans = list(ans.values())
        # ans.reverse()
        # return ans
        levelOrder = list()
        if not root:
            return levelOrder
        q = deque([root])
        while q:
            level = list()
            for _ in range(len(q)):
                node = q.popleft()
                level.append(node.val)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            levelOrder.append(level)
        return levelOrder[::-1]


if __name__ == '__main__':
    S = Solution()
    root = TreeNode(3)
    root.left = TreeNode(9)
    root.right = TreeNode(20)
    root.right.left = TreeNode(15)
    root.right.right = TreeNode(7)
    print(S.levelOrderBottom(root))
    print('done')
